package com.itcaius.myandroidhomework.ui;

import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.itcaius.myandroidhomework.MyApplication;
import com.itcaius.myandroidhomework.R;
import com.itcaius.myandroidhomework.data.callback.DatabaseCallback;
import com.itcaius.myandroidhomework.data.entity.UserEntity;
import com.itcaius.myandroidhomework.data.repo.UserRepository;
import com.itcaius.myandroidhomework.utils.Gender;


import java.util.ArrayList;


public class SignUpActivity extends AppCompatActivity {
    private EditText usernameEt;
    private EditText passwordEt;
    private Spinner citySpinner;
    private ListView cityList;
    private Button submitBtn;
    private RadioGroup sexRadioGroup;
    private Switch sex_switch;
    private UserRepository userRepo;
    //用于主线程执行代码
    private Handler mainThreadHandler = new Handler(Looper.getMainLooper());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //初始化代码
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signup);
        //获取UserRepo
        userRepo = ((MyApplication) getApplication()).getUserRepo();
        //初始化城市spinner
        citySpinner = findViewById(R.id.city_spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this,
                R.array.cities,
                android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        citySpinner.setAdapter(adapter);
        //要先转换为字符串数组
        String[] cities = getResources().getStringArray(R.array.cities);
        //初始化城市列表(操作和spinner一样)
        cityList = findViewById(R.id.city_list);
        ArrayAdapter<String> cityAdapter = new ArrayAdapter<>(
                this,
                R.layout.item_city,
                R.id.tv_item,
                cities
        );
        cityList.setAdapter(adapter);

        //监听用户名输入
        usernameEt = findViewById(R.id.username_et);
        //监听用户密码
        passwordEt = findViewById(R.id.password_et);
        //性别信息(逻辑判断后面处理)
        sexRadioGroup = findViewById(R.id.layout_sex_choice);
        //监听是否展示性别(要在点击事件里面进行数据的监听,在onCreate只会监听一次)
        sex_switch = findViewById(R.id.sex_switch);

        //点击提交时间实现数据展示
        submitBtn = findViewById(R.id.submit_btn);
        submitBtn.setOnClickListener(v -> {

            String username = usernameEt.getText().toString();
            String password = passwordEt.getText().toString();
            if (username.isEmpty()) {
                new AlertDialog.Builder(this)
                        .setTitle("用户名不能为空\uD83E\uDD17")
                        .setPositiveButton("确定", null)
                        .show();
                return;
            }
            if (password.isEmpty()) {
                new AlertDialog.Builder(this)
                        .setTitle("密码不能为空\uD83E\uDD10")
                        .setPositiveButton("确定", null)
                        .show();
                return;
            }
            int selectId = sexRadioGroup.getCheckedRadioButtonId();
            Gender gender = (selectId == R.id.sex_rb_man) ? Gender.MALE : Gender.FEMALE;

            UserEntity userEntity = new UserEntity(username, password, gender);
            userRepo.getUser(username, new DatabaseCallback<UserEntity>() {
                @Override
                public void onDataLoaded(UserEntity data) {
                    mainThreadHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (data == null) {
                                //用户名对应用户不存在，可以创建
                                userRepo.insertUser(userEntity);
                                Toast.makeText(SignUpActivity.this, "用户创建成功", Toast.LENGTH_LONG).show();
                            } else {
                                //用户名对应用户存在，不能创建
                                Toast.makeText(SignUpActivity.this, "该用户名的用户存在", Toast.LENGTH_LONG).show();
                                return;
                            }
                        }
                    });
                }

                @Override
                public void onError(Throwable error) {
                    mainThreadHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(SignUpActivity.this, "用户创建失败", Toast.LENGTH_LONG).show();
                        }
                    });
                }
            });

            //编辑输出数据
            StringBuilder sb = new StringBuilder();

            boolean checked = sex_switch.isChecked();
            if (checked) {
                if (gender == Gender.MALE) {
                    sb.append("泥蚝啊，" + username + "靓仔").append("\n");
                } else {
                    sb.append("欢迎" + username + "妹子光临~~~").append("\n");
                }
            } else {
                sb.append("欢迎光临\uD83C\uDF89").append("\n");
            }

            //监听兴趣爱好
            ArrayList<String> hobbies = new ArrayList<>();
            if (((CheckBox) findViewById(R.id.cb_music)).isChecked()) hobbies.add("音乐");
            if (((CheckBox) findViewById(R.id.cb_coding)).isChecked()) hobbies.add("编程");
            if (((CheckBox) findViewById(R.id.cb_read)).isChecked()) hobbies.add("阅读");
            if (((CheckBox) findViewById(R.id.cb_movie)).isChecked()) hobbies.add("电影");

            //监听城市选择
            String city = citySpinner.getSelectedItem().toString();
            sb.append("你现在是在" + city).append("\n");
            sb.append("你的兴趣爱好有：" + String.join("✧", hobbies)).append("\n");


            //显示数据
            new AlertDialog.Builder(this)
                    .setTitle("注册成功 \uD83C\uDF89")
                    .setMessage(sb.toString())
                    .setPositiveButton("确定", null)
                    .show();
        });
    }

}
